<template>
  <div>
    <el-upload
        class="dl-upload-box"
      :action="action"
      :headers="formHeader"
      :multiple="true"
      :data="formData"
      name="img"
      :limit="maxLimit"
      :file-list="fileListNew"
      list-type="picture-card"
      :before-upload="beforeUpload"
      :on-success="handleSuccess"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
    >
      <i class="el-icon-plus" />
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="showUrl" alt="">
    </el-dialog>
    <p style="color:#888;margin:0" v-if="tip">{{tip}}</p>
  </div>
</template>

<script>
import { getToken } from '@/utils/token'
import md5 from 'js-md5'
import { endecrypt } from '@/utils/aes_endecrypt'

export default {
  name: 'UploadAll',
  props: {
    formData:{
      type: Object,
      default: {}
    },
    fileList:{
      type: Array,
      default: []
    },
    maxLimit:{
      type: Number,
      default: 50
    },
    tip:{
      type: String,
      default: ''
    },
  },
  data() {
    return {
      dialogVisible: false,
      action: process.env.VUE_APP_BASE_API + "common.upload/upload_one.html",
      formHeader: {
      	token: getToken(),
      	apiKey: process.env.VUE_APP_BASE_API_KEY,
      },
      /*formData: {
      	dir_type: "",//上传路径
        file_name: "",//上传文件名(固定)
        allow_type: "",//允许上传的文件后缀（多个逗号隔开）
        file_size: "",//允许上传文件大小
      },*/
      //fileList: [], //已上传文件列表
      //maxLimit: 50,//最大允许上传个数
      showUrl: '',//显示文件url
      formUrl: '', //form文件url
      fileListNew: [],
    }
  },
  watch: {
      fileList: "urlHandle"
  },
  methods: {
    //文件url处理
    urlHandle(newVal, oldVal) {
      this.fileListNew = [];
      if (this.fileList.length > 0) {
        this.fileList.forEach((item) => {
          this.fileListNew.push({ name: item, url: item });
        });
      }
    },
    //上传文件之前的钩子
    beforeUpload(file) {
      //formHeader 参数
      //请求时间戳
      let timeStamp = Math.round(new Date() /1000)
      this.formHeader.timeStamp = timeStamp
      this.formHeader.sign = md5(process.env.VUE_APP_BASE_API_KEY+process.env.VUE_APP_BASE_API_SECRET+timeStamp).toUpperCase()
    },
    // 图片上传成功
    handleSuccess(response, file, fileList) {
      let that = this;
      let imgArr = [];
      fileList.forEach(item => {
        //解密
        if(typeof(item.response.datas) == 'string'){
          item.response.datas = endecrypt(item.response.datas, true)
        }
        if(item.response){
          if (item.response.code == 200) {
            imgArr.push(item.response.datas.file_name);
          }else{
            that.$message(item.response.datas.error);
            return false;
          }
        }else{
          let str = '/' + item.url.split('/').slice(3).join('/');
          imgArr.push(str);
        }
      });
      that.formUrl = imgArr.join(',');
      //返回数据
      that.$emit('uploadCallBack', {fileName: that.formUrl});
    },
    // 图片删除
    handleRemove(file,fileList) {
      let imgArr = [];
      fileList.forEach(item => {
        if (item.response) {
        	if (item.response.code == 200) {
        		imgArr.push(item.response.datas.file_name);
        	}
        }else{
        	let str = '/' + item.url.split('/').slice(3).join('/');
        	imgArr.push(str);
        }
      });
      this.formUrl = imgArr.join(',');
      //返回数据
      this.$emit('uploadCallBack', {fileName: this.formUrl});
    },
    // 图片放大
    handlePictureCardPreview(file) {
      this.showUrl = file.url;
      this.dialogVisible = true;
    }
  }
}
</script>

<style type="text/css">
  .dl-upload-box .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    overflow: hidden;
    width: 100px;
    height: 100px;
    line-height: 100px;
  }
  .dl-upload-box .el-upload:hover {
    border-color: #409EFF;
  }
  .dl-upload-box .el-upload-list .el-upload-list__item {
    width: 100px;
    height: 100px;
  }
</style>
